package com.loong.aspect;

import com.alibaba.fastjson.JSONObject;
import com.loong.entity.OperateLog;
import com.loong.mapper.OperateLogMapper;
import com.loong.utils.CurrentHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.Arrays;

@Aspect
@Component
@Slf4j
public class LogAspect {
    @Autowired
    private OperateLogMapper operateLogMapper;

    @Pointcut("execution(* com.loong.controller.*Controller.insert(..))")
    private void ptInsert() {}

    @Pointcut("execution(* com.loong.controller.*Controller.update(..))")
    private void ptUpdate() {}

    @Pointcut("execution(* com.loong.controller.*Controller.delete(..))")
    private void ptDelete() {}

    @Pointcut("execution(* com.loong.controller.StudentController.violation(..))")
    private void ptViolation() {}

    @Around("ptInsert() || ptUpdate() || ptDelete() || ptViolation()")
    public Object recordLog(ProceedingJoinPoint joinPoint) throws Throwable {
        OperateLog operateLog = new OperateLog();

        long begin = System.currentTimeMillis();
        Object result = joinPoint.proceed();
        long end = System.currentTimeMillis();
        operateLog.setCostTime(end - begin);

        operateLog.setOperateEmpId(CurrentHolder.getCurrentId());
        operateLog.setOperateTime(LocalDateTime.now());
        operateLog.setClassName(joinPoint.getTarget().getClass().getName());
        operateLog.setMethodName(joinPoint.getSignature().getName());
        operateLog.setMethodParams(Arrays.toString(joinPoint.getArgs()));

        operateLog.setReturnValue(JSONObject.toJSONString(result));

        operateLogMapper.insert(operateLog);
        log.info("记录操作日志: {}", operateLog);
        return result;
    }
}
